package models

import (
	"fmt"
	"gin-ebook/Databases"
)

var (
	db = Databases.DB
)

type Book struct {
	//Databases.Model

	//TagID int `json:"tag_id"`
	//Tag   Tag `json:"tag"`
	Id        int    `json:"id"`
	Title     string `json:"title"`
	Desc      string `json:"desc"`
	Author    string `json:"author"`
	Category  string `json:"category"`
	Language  string `json:"language"`
	Publisher string `json:"publisher"`
	Read      int    `json:"read"`
	Cover     string `json:"cover"`
	Epub      string `json:"epub"`
	Number    string `json:"number"`
	Score     string `json:"score"`
	//State     int    `json:"state"`
}

func AddArticle(data map[string]interface{}) {
	//article := Article{
	//	TagID:     data["tag_id"].(int),
	//	Title:     data["title"].(string),
	//	Desc:      data["desc"].(string),
	//	Content:   data["content"].(string),
	//	CreatedBy: data["created_by"].(string),
	//	State:     data["state"].(int),
	//}
	//db.Create(&article)
}
func DeleteArticle(id int) {
	//db.Where("id = ?", id).Delete(Article{})
}

//id查找是否存在文章
func ExistArticleByID(id int) bool {
	var book Book
	db.Select("id").Where("id = ?", id).First(&book)

	if book.Id > 0 {
		return true
	}
	return false
}

//编辑文章
func EditArticle(id int, data map[string]interface{}) {
	//db.Model(&Article{}).Where("id = ?", id).Updates(data)
}

// 获取单个文章
func GetArticle(id int) (book Book) {
	db.Where("id = ?", id).Preload("Tag").First(&book)
	// 关联查询
	db.Model(&book).Association("Tag")
	return
}

// 获取单个文章
func GetBookDetail(id int) (book Book) {
	db.Where("id = ?", id).First(&book)
	// 关联查询
	//db.Model(&book).Association("Tag")
	return
}

// 获取文章列表
func GetBooks(pageNum int, pageSize int, maps interface{}) (book []Book) {
	db.Where(maps).Limit(pageSize).Offset(pageNum).Find(&book)
	return
}

// 获取指定分类的图书
func GetCategoryBooks(id int) (book []Book) {
	db.Where("category = ?", id).Find(&book)
	return
}

func GetHotBooks(pageNum int, pageSize int, maps interface{}) (book []Book) {
	db.Order("title desc").Find(&book)
	return
}
func GetRecommendBooks(pageNum int, pageSize int, maps interface{}) (book []Book) {
	a := db.Order("author desc").Find(&book)
	fmt.Println(a, "sadasda")
	return
}

func GetBookTotal(maps interface{}) (count int64) {
	db.Model(&Book{}).Where(maps).Count(&count)
	return
}

//func (book *Book) BeforeCreate(tx *gorm.DB) (err error) {
//
//	book.CreatedOn = time.Now().Unix()
//	log.Println(book.CreatedOn)
//
//	return
//}

// hook
//func (book *Book) BeforeUpdate(tx *gorm.DB) (err error) {
//
//	book.CreatedOn = time.Now().Unix()
//	log.Println(book.CreatedOn)
//
//	return
//}

// 搜索功能实现
func SearchBook(title string) (books []Book) {
	db.Where("title LIKE ?", "%"+title+"%").Find(&books)
	return
}
